# coding:utf-8
from django.http import HttpResponse
import os, json, re
import cv2

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def preprocess(path):
    # 加载图片到内存
    img = cv2.imread(path, cv2.IMREAD_COLOR)
    # 获取图像的高度 宽度 通道数
    h, w, ch = img.shape
    # 将高度大于600 或宽度大于900 的图片缩小一半
    while h > 600 or w > 900:
        img = cv2.resize(img, (int(w / 2), int(h / 2)), interpolation=cv2.INTER_CUBIC)
        h, w, ch = img.shape
    cv2.imwrite(path, img)
    return 'success'


def save_file_image(request):
    file_path = ''
    if request.method == "POST":
        file_img = request.FILES.get('file')
        if re.match(r'.+\.(jpg|png|jpeg|gif|bmp)$', str(file_img), re.I):
            print(file_img.name)
            with open(os.path.join(BASE_DIR, 'static', 'imgs', 'upload', file_img.name), 'wb') as f:
                for ck in file_img.chunks():
                    f.write(ck)
                file_path = f.name
                f.close()
            preprocess(file_path)
        else:
            return HttpResponse(json.dumps({"result": "fail"}))
    return HttpResponse(json.dumps({"result": "success", "path": file_path.split("cherry")[1]}))
